- Published on
Performing a search operation
- Authors
- Name
Searching
People use various search techniques to find content on their device, within an app, and within a document or file.
人们使用各种搜索技巧来查找设备上的内容、应用程序内的内容以及文档或文件中的内容。
To search for content within an app, people generally expect to use a search bar. When it makes sense, you can personalize the search experience by using what you know about people interact with your app. For example, you might display recent searches or a search history, or offer search-term suggestions, completions, or corrections based on terms people searched earlier in your app. For guidance, see Search fields.
人们通常期望通过使用搜索栏(search bar)来查找应用程序内的内容。在适当的情况下,你可以根据用户如何与应用程序互动来个性化搜索体验。例如,你可以显示最近的搜索或搜索历史,或者根据用户之前在应用程序中搜索的词语提供搜索词建议、自动补全或纠错。有关指导,请参阅 Search fields。
In some cases, people appreciate the ability to scope a search or filter the results, For example, people might want to search for items by specifying attributes like creation date, file size, or file type. For guidance, see Scope bars. You can also help people find content within an open document or file by implementing ways to find content in a window or page in your iOS, iPadOS, or macOS app.
有些时候,人们会希望能够限定搜索范围
Update search results based on search text and optional tokens that you store.
Overview
To conduct a search in your app's data model,create storage for the query text and present it with a searchable view modifier. Because you manage the storage, you can detect when it changes and update the search operation in response, By updating search results as people type, you ensure that your app's search interface is responsive.
you can also optionally provide storage for tokens, which are discreate search terms that your app recognizes. Tokens provide a way to combine multiple search terms, and make it easier for you to indicate that a search term is common or expected in your app.
https://docs-assets.developer.apple.com/published/2139de17579d7f0ab113083751fc86b8/[email protected]
For information on how to control the placement of the search field in your app's interface, see Adding a search interface to you app.
Provide storage for a string
The searchable modifier take a Binding to a string value for the text input. The string serves as the storage for the search query field that SwiftUI displays. You can create this storage inside a view using a State property, and initialize it to an empty string:
@State private var searchText: String = ""
To make it easier to share the search query among different views, you can create a published value inside an observable object that's part of your app's model:
class Model: ObservableObject {
@Published var searchText: String = ""
}